package com.engineering.elink.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.engineering.elink.co.BaseCo;
import com.engineering.elink.common.ErrorType;
import com.engineering.elink.common.Pagination;
import com.engineering.elink.dao.CollectionMapper;
import com.engineering.elink.dao.FileMapper;
import com.engineering.elink.domain.Collection;
import com.engineering.elink.domain.File;
import com.engineering.elink.service.CollectionService;
import com.engineering.elink.util.JSONUtil;

@Service
public class CollectionServiceImpl implements CollectionService {
	@Autowired
	private CollectionMapper collectionMapper;
	@Autowired
	private FileMapper fileMapper;
	
	@Override
	public Map<String, Object> updateCollect(String userId, String fileId) {
		File f = fileMapper.selectByPrimaryKey(fileId);
		if(f != null ){
			int count = collectionMapper.select(userId,fileId);
			if(count == 0 ){ //表示没有收藏过
				Collection c = new Collection();
				c.setUserId(userId);
				c.setFileId(fileId);
				c.setCollectionTime(new Date());
				collectionMapper.insertSelective(c);
				//文件的收藏数加一
				f.setCollectionCount(f.getCollectionCount()+1);
				fileMapper.updateByPrimaryKeySelective(f);
				
				return JSONUtil.getJSON(ErrorType.COLLECTION_SUCCESS);
			}else{
				collectionMapper.delete(userId,fileId);
				//文件的收藏数减1
				f.setCollectionCount(f.getCollectionCount()-1);
				fileMapper.updateByPrimaryKeySelective(f);
				
				return JSONUtil.getJSON(ErrorType.CANCEL_COLLECTION);
			}
			
		}else{
			return JSONUtil.getJSON(ErrorType.FILE_COMMENT_ERROR);
		}
	}

	@Override
	public Map<String, Object> getMyCollect(BaseCo co,String userId) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("list", fileMapper.getMyCollect(co,userId));
		map.put("Pagination",   new Pagination(co, fileMapper.selectCountMyCollect(userId)) );
		
		return JSONUtil.getJSON(ErrorType.SUCCESS,map);
	}

}
